package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.BusServiceItem;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.BusServiceItemMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.BusServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.IBusServiceItemService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class BusServiceItemServiceImpl implements IBusServiceItemService {

    @Autowired
    private BusServiceItemMapper busServiceItemMapper;
    @Autowired
    private CarPackageAuditMapper carPackageAuditService;
    @Autowired
    private BpmnInfoMapper bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;
    @Override
    public void save(BusServiceItem busServiceItem) {
        BusServiceItem obj = new BusServiceItem();
        obj.setName(busServiceItem.getName());
        obj.setOriginalPrice(busServiceItem.getOriginalPrice());
        obj.setDiscountPrice(busServiceItem.getDiscountPrice());
        obj.setCarPackage(busServiceItem.getCarPackage());
        obj.setServiceCatalog(busServiceItem.getServiceCatalog());
        obj.setInfo(busServiceItem.getInfo());
        obj.setCreateTime(new Date());
        if (BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage())){
            obj.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
        }else {
            obj.setAuditStatus(BusServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        busServiceItemMapper.insert(obj);
    }

    @Override
    public BusServiceItem get(Long id) {
        return busServiceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BusServiceItem busServiceItem) {
        BusServiceItem obj=this.get(busServiceItem.getId());
        if (BusServiceItem.SALESTATUS_ON.equals(obj.getSaleStatus())){
            throw  new BusinessException("上架用户不可以修改");
        }
        if (BusServiceItem.CARPACKAGE_YES.equals(obj.getCarPackage()) && ! BusServiceItem.AUDITSTATUS_APPROVED.equals(obj.getAuditStatus())){
                throw new BusinessException("未通过审核的套餐不可以修改");
        }
        busServiceItemMapper.updateByPrimaryKey(busServiceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            busServiceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BusServiceItem> list() {
        return busServiceItemMapper.selectAll();
    }
    @Override
    public TablePageInfo<BusServiceItem> query(BusServiceItemQuery qo) {
//        if (qo.getName()!=null && qo.getName()!="") {
//            qo.setName(qo.getName().substring(0, qo.getName().lastIndexOf(",")));
//        }
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        List<BusServiceItem> busServiceItems = busServiceItemMapper.selectForList(qo);
        return new TablePageInfo<BusServiceItem>(busServiceItems);
    }

    @Override
    public void saleOn(Long id) {
        BusServiceItem busServiceItem = busServiceItemMapper.selectByPrimaryKey(id);
        if (BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage()) && !BusServiceItem.AUDITSTATUS_APPROVED.equals(busServiceItem.getAuditStatus())){
            throw new BusinessException("套餐需要审核通过才能上架");
        }
        busServiceItem.setSaleStatus(BusServiceItem.SALESTATUS_ON);
        busServiceItemMapper.updateByPrimaryKey(busServiceItem);
    }

    @Override
    public void saleOff(Long id) {
        BusServiceItem busServiceItem = busServiceItemMapper.selectByPrimaryKey(id);
        busServiceItem.setSaleStatus(BusServiceItem.SALESTATUS_OFF);
        busServiceItemMapper.updateByPrimaryKey(busServiceItem);
    }

    @Override
    @Transactional
    public void startAudit(Long id, Long shopOwnerId, Long financialId, String info) {
        //有什么样的限制条件
            //根据服务单项的id查询服务单项,判断状态是否处于初始化或者重新调整
            //需要封装CarPackageAudit信息
            //获取插入数据库中的id的值
            //如何找到对应流程定义,发起流程实例
            //通过CarPackageAudit.AUDIT_TYPE_TYPE去bpmninfo表中查询记录
            //如果返回null,说明没有上传流程定义.
            //如果有多个,按照部署时间取最近部署的那个
            //流程定义的key
            //发起流程的时候需要携带审核参数到流程中
            //需要定义Map集合,存储店长id,财务id,折扣金额
            //启动流程实例,业务key和流程变量的启动的时候一并传入
            // 将运行实例的 id 设置进入CarPackageAudit
            //服务单项的状态怎么改变呢
            //改变审核中
            //CarPackageAudit信息需要设置instanceId
        BusServiceItem busServiceItem = this.get(id);
        if (BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage())
        && BusServiceItem.AUDITSTATUS_INIT.equals(busServiceItem.getAuditStatus()) || BusServiceItem.AUDITSTATUS_REPLY.equals(busServiceItem.getAuditStatus())){
            CarPackageAudit audit = new CarPackageAudit();
            audit.setServiceItemId(busServiceItem.getId());
            audit.setServiceItemName(busServiceItem.getName());
            audit.setServiceItemInfo(busServiceItem.getInfo());
            audit.setServiceItemPrice(busServiceItem.getOriginalPrice());
            audit.setCreatorId(String.valueOf(ShiroUtils.getUserId()));
            audit.setInfo(info);
            audit.setCreateTime(new Date());
            carPackageAuditService.insert(audit);
            BpmnInfo byBpmnType = bpmnInfoService.getByBpmnType(CarPackageAudit.AUDIT_TYPE);
            if (byBpmnType==null){
                throw new BusinessException("请先定义流程");
            }
            String businessKey=String.valueOf(audit.getId());
            Map<String,Object> map=new HashMap<>();
            map.put("shopOwnerId",shopOwnerId);
            map.put("financeId",financialId);
            map.put("disCountPrice",busServiceItem.getDiscountPrice().longValue());
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(byBpmnType.getProcessDefinitionKey(), businessKey, map);
            audit.setInstanceId(processInstance.getProcessInstanceId());
            carPackageAuditService.updateByPrimaryKey(audit);
            busServiceItemMapper.changeStatus(busServiceItem.getId(),BusServiceItem.AUDITSTATUS_AUDITING);
        }else {
            throw new BusinessException("只有套餐且必须为初始化或重新审核才可以发起审核");
        }

    }

    @Override
    public void changeStatus(Long serviceItemId, Integer auditstatusInit) {
        busServiceItemMapper.changeStatus(serviceItemId,auditstatusInit);
    }
}
